﻿using Chromely.Core;
using Chromely.Core.Configuration;
using Chromely.Core.Host;
using Chromely.Core.Logging;
using Reader.Core.Application;
using Reader.Core.Application.Models;
using Reader.Core.DataAccessObject.Models;
using Reader.Core.Shell32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Xilium.CefGlue.Wrapper;

namespace Reader.Controllers.Message
{
    public class BookController : ProcessController
    {
        private readonly IChromelyConfiguration _config;
        private readonly IChromelyContainer _container;
        private readonly IChromelyWindow _window;
        private readonly Applications _applications;
        public BookController(IChromelyConfiguration config, IChromelyContainer container, IChromelyWindow window)
        {
            _config = config;
            _container = container;
            _window = window;
            var obj = container.GetAllInstances(typeof(Applications)).SingleOrDefault();
            if(obj != null && obj is Applications)
            {
                _applications = obj as Applications;
            }
        }
        public async Task<List<BookSite>> getSites()
        {
            var result = await _applications.Sites.GetSites();
            if (result.Success)
            {
                return result.Data;
            }
            else
            {
                throw new Exception(result.Message);
            }
        }
        public async Task<Result<dynamic>> getBook(int id)
        {
            return await _applications.Books.GetBookAsync(id);
        }
        public async Task<Result<dynamic>> getBookUpdate(int id)
        {
            return await _applications.Books.GetBookUpdateAsync(id);
        }
        public async Task<Result<int>> newBook(NewBookModel newBook)
        {
            return await _applications.Books.NewBookAsync(newBook);
        }
        public async Task<Result> newBookChapter(CreateChapterModel model)
        {
            if(model.Last == null)
            {
                return await _applications.Books.CreateChapterAsync(model);
            }
            else
            {
                return await _applications.Books.UpdateBookAsync(model);
            }
        }
        public async Task<Result> deleteBook(int id)
        {
            return await _applications.Books.RemoveBook(id);
        }
        public async Task<List<BookInfoSource>> getSource()
        {
            return await _applications.Books.GetBookInfoSourceAsync();
        }
        public async Task access(string url)
        {
            await _applications.Books.Access(url);
        }
        public async Task<string> getReadPosition(int id)
        {
            return await _applications.Books.GetReadPosition(id);
        }
        public async Task downloadFile(int id)
        {
            await _applications.Books.DownloadFile(id);
        }
    }
}
